package com.avic.rong.questionOrAnswer;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avic.rong.R;
import com.avic.rong.questionOrAnswer.activity.AnswerDetailsActivity;
import com.avic.rong.questionOrAnswer.activity.PersonalHomeActivity;
import com.avic.rong.questionOrAnswer.api.AnswerThumbNumApi;
import com.avic.rong.questionOrAnswer.api.CancelThumbApi;
import com.avic.rong.questionOrAnswer.api.CancelnCollectionApi;
import com.avic.rong.questionOrAnswer.api.CollectApi;
import com.avic.rong.questionOrAnswer.api.QuestionCollectNumApi;
import com.avic.rong.questionOrAnswer.api.ThumbApi;
import com.avic.rong.questionOrAnswer.bean.QaaMyListBean;
import com.avic.rong.userOrder.api.AnswerCollectNumApi;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.GlideUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.FolderTextView;
import com.bumptech.glide.Glide;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by XinEr on 2019/8/13.
 * Describe:
 */
public class AnswerViewHolder extends RecyclerView.ViewHolder {
    private ImageView ic_photo;
    private TextView tv_name;
    private TextView tv_date;
    private TextView tv_sign;
    private TextView tv_question_content;
    private FolderTextView tv_answer;
    private TextView tv_collect_num;
    private LinearLayout ll_collect;
    private TextView tv_zan_num;
    private LinearLayout ll_zan;
    private TextView tv_comment_num;
    private LinearLayout ll_comment;
    private LinearLayout ll_root;
    private ImageView iv_collect;
    private ImageView iv_zan;
    private ImageView iv_attestation;
    public View line;

    private int thumb = -1;
    private int clickPos = -1;
    private int contId;
    private Context context;

    public AnswerViewHolder(@NonNull View itemView) {
        super(itemView);
        ic_photo = itemView.findViewById(R.id.ic_photo);
        tv_name = itemView.findViewById(R.id.tv_name);
        tv_date = itemView.findViewById(R.id.tv_date);
        tv_sign = itemView.findViewById(R.id.tv_sign);
        tv_question_content = itemView.findViewById(R.id.tv_question_content);
        tv_answer = itemView.findViewById(R.id.tv_answer);
        tv_collect_num = itemView.findViewById(R.id.tv_collect_num);
        ll_collect = itemView.findViewById(R.id.ll_collect);
        tv_zan_num = itemView.findViewById(R.id.tv_zan_num);
        ll_zan = itemView.findViewById(R.id.ll_zan);
        tv_comment_num = itemView.findViewById(R.id.tv_comment_num);
        ll_comment = itemView.findViewById(R.id.ll_comment);
        iv_collect = itemView.findViewById(R.id.iv_collect);
        iv_zan = itemView.findViewById(R.id.iv_zan);
        ll_root = itemView.findViewById(R.id.ll_root);
        iv_attestation = itemView.findViewById(R.id.iv_attestation);
        line = itemView.findViewById(R.id.line);
    }

    public void setData(QaaMyListBean qaaMyListBean, final Context context) {
        this.context = context;
        if (qaaMyListBean.getContent().contains("<br>")) {
            String content = qaaMyListBean.getContent().replaceAll("<br>", "\n");
            tv_answer.setText(content);
        } else {
            tv_answer.setText(qaaMyListBean.getContent());
        }
        if (!TextUtils.isEmpty(qaaMyListBean.getPublicTime1())) {
            String data = stampToDate(Long.parseLong(qaaMyListBean.getPublicTime1()));
            tv_date.setText(data);
        }
        tv_question_content.setText("回答了： " + qaaMyListBean.getTitle() + "");
        tv_collect_num.setText(qaaMyListBean.getCollectNum() + "");
        tv_comment_num.setText(qaaMyListBean.getAppraiseNum() + "");
        tv_zan_num.setText(qaaMyListBean.getNiceNum() + "");
        if (!TextUtils.isEmpty(((PersonalHomeActivity)context).getLOGO())) {
            GlideUtils.loaderHanldeRoundImage(context, ((PersonalHomeActivity)context).getLOGO(), ic_photo, 80);
        } else {
            Glide.with(context).load(R.mipmap.ic_default_head).into(ic_photo);
        }
        if (!TextUtils.isEmpty(((PersonalHomeActivity)context).getNAME())) {
            tv_name.setText(((PersonalHomeActivity)context).getNAME());
        }
        if (!TextUtils.isEmpty(((PersonalHomeActivity)context).getAuthenticationInformation())) {
            tv_sign.setText(((PersonalHomeActivity)context).getAuthenticationInformation());
        }
        if (1==((PersonalHomeActivity)context).getISV()){
            iv_attestation.setVisibility(View.VISIBLE);
        }


        //是否点赞
        if (qaaMyListBean.isThumb()) {
            iv_zan.setSelected(true);
        } else {
            iv_zan.setSelected(false);
        }


        //是否收藏
        if (qaaMyListBean.isFavorite()) {
            iv_collect.setSelected(true);
        } else {
            iv_collect.setSelected(false);
        }
        ll_zan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                contId = qaaMyListBean.getId();
                if (iv_zan.isSelected()) {
                    unZanReq(contId, context);
                } else {
                    zanReq(contId, context);
                }
            }
        });

        ll_collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                contId = qaaMyListBean.getId();
                if (iv_collect.isSelected()) {
                    unCollectReq(contId, context);
                } else {
                    collectReq(contId, context);
                }
            }
        });
        ll_root.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                context.startActivity(AnswerDetailsActivity.queryIntent(context, qaaMyListBean.getId() + ""));
            }
        });
        tv_answer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                context.startActivity(AnswerDetailsActivity.queryIntent(context, qaaMyListBean.getId() + ""));
            }
        });

    }

    private void collectReq(int contId, Context context) {
        PersonalHomeActivity personalHomeActivity = (PersonalHomeActivity) context;
        Map<String, String> map = new HashMap<>();

        if (contId <= 0 && TextUtils.isEmpty(SharedPreferencesUtil.getLoginToken())) {
            return;
        }
        map.put("targetId", contId + "");

        //收藏对象类型（1：软件服务  2：元器件 3：元器件审核备案 4：元器件试验检测  5：培训 6：标准 7：标准知识 8:企业 12:文章13:提问 14:回答）
        map.put("favoritesFlag", 14 + "");

        map.put("token", SharedPreferencesUtil.getLoginToken());
        final CollectApi collectApi = new CollectApi(personalHomeActivity, simpleOnNextListenerCollect);
        collectApi.setCache(false);
        collectApi.setMap(map);
        HttpManager.getInstance().doHttpDeal(collectApi);
    }

    private void unCollectReq(int contId, Context context) {
        PersonalHomeActivity personalHomeActivity = (PersonalHomeActivity) context;
        Map<String, String> map = new HashMap<>();

        if (contId <= 0 && TextUtils.isEmpty(SharedPreferencesUtil.getLoginToken())) {
            return;
        }

        map.put("targetId", contId + "");

        //收藏对象类型（1：软件服务  2：元器件 3：元器件审核备案 4：元器件试验检测  5：培训 6：标准 7：标准知识 8:企业 12:文章13:提问 14:回答）
        map.put("favoritesFlag", 14 + "");

        map.put("token", SharedPreferencesUtil.getLoginToken());
        final CancelnCollectionApi cancelnCollectionApi = new CancelnCollectionApi(personalHomeActivity, simpleOnNextListenerUnCollect);
        cancelnCollectionApi.setCache(false);
        cancelnCollectionApi.setMap(map);
        HttpManager.getInstance().doHttpDeal(cancelnCollectionApi);
    }

    private void unZanReq(int contId, Context context) {
        PersonalHomeActivity personalHomeActivity = (PersonalHomeActivity) context;
        Map<String, String> map = new HashMap<>();

        if (contId <= 0 && TextUtils.isEmpty(SharedPreferencesUtil.getLoginToken())) {
            return;
        }

        map.put("contId", contId + "");

        //新闻1提问2回答3
        map.put("type", 3 + "");

        map.put("token", SharedPreferencesUtil.getLoginToken());
        final CancelThumbApi cancelThumbApi = new CancelThumbApi(personalHomeActivity, simpleOnNextListenerUnZan);
        cancelThumbApi.setCache(false);
        cancelThumbApi.setMap(map);
        HttpManager.getInstance().doHttpDeal(cancelThumbApi);


    }

    private void zanReq(int contId, Context context) {

        PersonalHomeActivity personalHomeActivity = (PersonalHomeActivity) context;
        Map<String, String> map = new HashMap<>();

        if (contId <= 0 && TextUtils.isEmpty(SharedPreferencesUtil.getLoginToken())) {
            return;
        }

        map.put("contId", contId + "");
        //
        //新闻1提问2回答3
        map.put("type", 3 + "");
        map.put("token", SharedPreferencesUtil.getLoginToken());
        final ThumbApi thumbApi = new ThumbApi(personalHomeActivity, simpleOnNextListener);
        thumbApi.setCache(false);
        thumbApi.setMap(map);
        HttpManager.getInstance().doHttpDeal(thumbApi);


    }

    //取消收藏
    HttpOnNextListener simpleOnNextListenerUnCollect = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                if (subjects.getCode().equals("1008")) {
                    ToastTools.showToast(context, "取消收藏失败");
                } else {
                    ToastTools.showToast(context, subjects.getMsg());
                }

                return;
            }
            ToastTools.showToast(context, "取消收藏成功");
            Integer num = ((Double) subjects.getData()).intValue();
//            Integer num = Integer.parseInt(subjects.getData().toString());
            tv_collect_num.setText(num + "");
            iv_collect.setSelected(false);
//            questionCollectNum();
            answerCollectNum();

        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };
    //收藏
    HttpOnNextListener simpleOnNextListenerCollect = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_1000)) {
                ToastTools.showToast(context, subjects.getMsg());
                return;
            }
            ToastTools.showToast(context, "收藏成功");
            Integer num = ((Double) subjects.getData()).intValue();
//            Integer num = Integer.parseInt(subjects.getData().toString());
            tv_collect_num.setText(num + "");
            iv_collect.setSelected(true);
//            questionCollectNum();
            answerCollectNum();

        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };

    private void answerCollectNum() {
        PersonalHomeActivity personalHomeActivity = (PersonalHomeActivity) context;
        Map<String, String> map = new HashMap<>();

        if (contId <= 0) {
            return;
        }
        map.put("ansId", contId + "");

        final AnswerCollectNumApi answerCollectNumApi = new AnswerCollectNumApi(personalHomeActivity, simpleOnNextListenerAnswerCollectNum);
        answerCollectNumApi.setCache(false);
        answerCollectNumApi.setMap(map);
        HttpManager.getInstance().doHttpDeal(answerCollectNumApi);
    }

    private void questionCollectNum() {
        PersonalHomeActivity personalHomeActivity = (PersonalHomeActivity) context;
        Map<String, String> map = new HashMap<>();

        if (contId <= 0) {
            return;
        }
        map.put("queId", contId + "");

        final QuestionCollectNumApi questionCollectNumApi = new QuestionCollectNumApi(personalHomeActivity, simpleOnNextListenerCollectNum);
        questionCollectNumApi.setCache(false);
        questionCollectNumApi.setMap(map);
        HttpManager.getInstance().doHttpDeal(questionCollectNumApi);
    }

    //点赞
    HttpOnNextListener simpleOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
                ToastTools.showToast(context, subjects.getMsg());
                return;
            }
            ToastTools.showToast(context, "点赞成功");
            Integer num = ((Double) subjects.getData()).intValue();
//            Integer num = Integer.parseInt(subjects.getData().toString());
            tv_zan_num.setText(num + "");
            iv_zan.setSelected(true);
            thumbNum();

        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };
    //取消点赞
    HttpOnNextListener simpleOnNextListenerUnZan = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
                ToastTools.showToast(context, subjects.getMsg());
                return;
            }

            ToastTools.showToast(context, "取消点赞成功");
            Integer num = ((Double) subjects.getData()).intValue();
//            Integer num = Integer.parseInt(subjects.getData().toString());
            tv_zan_num.setText(num + "");
            iv_zan.setSelected(false);
            thumbNum();
        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };

    private void thumbNum() {
        PersonalHomeActivity personalHomeActivity = (PersonalHomeActivity) context;
        Map<String, String> map = new HashMap<>();

        if (contId <= 0) {
            return;
        }
        map.put("ansId", contId + "");

        final AnswerThumbNumApi answerThumbNumApi = new AnswerThumbNumApi(personalHomeActivity, simpleOnNextListenerThumbNum);
        answerThumbNumApi.setCache(false);
        answerThumbNumApi.setMap(map);
        HttpManager.getInstance().doHttpDeal(answerThumbNumApi);
    }

    //回答点赞数变动
    HttpOnNextListener simpleOnNextListenerThumbNum = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
//                ToastTools.showToast(context, subjects.getMsg());
                return;
            }

        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };
    //问题收藏变动
    HttpOnNextListener simpleOnNextListenerCollectNum = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
//                ToastTools.showToast(context, subjects.getMsg());
                return;
            }

        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };
    //回答收藏变动
    HttpOnNextListener simpleOnNextListenerAnswerCollectNum = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
//                ToastTools.showToast(context, subjects.getMsg());
                return;
            }

        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };

    /*
     * 将时间戳转换为时间
     */
    public static String stampToDate(long timeMillis) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(timeMillis);
        return simpleDateFormat.format(date);
    }
}
